package by.grsu.kononovich.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.kononovich.entity.Administrator;
import by.grsu.kononovich.table.AdministratorTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class AdministratorDao extends AbstractDao<AdministratorTable, Administrator> {

	public AdministratorDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(Administrator newAdmin) {
		newAdmin.setId(getNextId());
		final AdministratorTable administratorTable = deserializeFromXml();
		administratorTable.getRows().add(newAdmin);
		serializeToXml(administratorTable);
	}

	@Override
	public void update(Administrator entity) {
		final AdministratorTable administratorTable = deserializeFromXml();
		for (final Administrator row : administratorTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				row.setName(entity.getName());
				row.setSurname(entity.getSurname());
				break;
			}
		}
		serializeToXml(administratorTable);
	}

	@Override
	public Administrator get(Serializable id) {
		final AdministratorTable administratorTable = deserializeFromXml();
		for (final Administrator row : administratorTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Administrator> getAll() {
		final AdministratorTable administratorTable = deserializeFromXml();
		return administratorTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final AdministratorTable administratorTable = deserializeFromXml();
		Administrator toBeDeleted = null;
		for (final Administrator row : administratorTable.getRows()) {
			if (row.getId().equals(id)) {
				toBeDeleted = row;
				break;
			}
		}
		administratorTable.getRows().remove(toBeDeleted);
		serializeToXml(administratorTable);
	}

	@Override
	protected Class<AdministratorTable> getTableClass() {
		return AdministratorTable.class;
	}

}
